class User < ActiveRecord::Base
  require "digest/sha1"
  
  acts_as_annotation_source
  
  has_many :shims
  
  validates_presence_of :name
  validates_presence_of :password
  validates_presence_of :email
  
  validates_length_of :name, :minimum => 5
  validates_length_of :email, :minimum => 8
  validates_length_of :password, :minimum => 6
  
  validates_uniqueness_of :email
  validates_uniqueness_of :name
  
  validates_confirmation_of :password
  validates_confirmation_of :email
  
#  validates_numericality_of :access, :only_integer => true,
#  :greater_than_or_equal_to => 0, :less_than_or_equal_to => 1, :default => 0
  
  attr_reader :password
  attr_accessor :password_confirmation
  attr_accessor :email_confirmation
  
  validates_format_of :email, 
  :with => /^(?:[_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-zA-Z0-9\-\.]+)*(\.[a-z]{2,4})$/i, 
  :message => "address has invalid format"
  
#  validates_format_of :name,
#  :with => /[^(admin)]/i,
#  :message => "name cannot contain ADMIN"
  
  validate :password_non_blank 
  
  before_save :set_access
  
  def password=(pwd) 
    @password = pwd 
    return if pwd.blank? 
    create_new_salt 
    self.crypted_password = User.encrypted_password(self.password, self.salt) 
  end 
  
  def self.authenticate(name, password) 
    user = self.find_by_name(name) 
    if user 
      expected_password = encrypted_password(password, user.salt) 
      if user.crypted_password != expected_password 
        user = nil 
      end 
    end 
    user 
  end 
  
  private
  
  def password_non_blank 
    errors.add(:password, "Missing password") if crypted_password.blank? 
  end
  
  def create_new_salt 
    self.salt = self.object_id.to_s + rand.to_s 
  end 
  
  def self.encrypted_password(password, salt) 
    string_to_hash = "--#{password}--#{salt}--" 
    Digest::SHA1.hexdigest(string_to_hash) 
  end 
  
  def set_access
    self.access = 0 if self.access.blank? || !self.access.between?(0,1)
    self.access = 1 if self.name=="Shims Library"
  end
end
